<template>
	<div class="table-box">
		<ProTable
			ref="useProTable"
			:rowKey="'t_user_id'"
			:columns="columns"
			:request-api="getUseProTableListApi"
			:search-col="{ xs: 1, sm: 1, md: 2, lg: 4, xl: 5 }"
		>
			<!-- 表格header按钮 -->
			<template #tableHeader="scope">
				<el-button type="primary" :icon="CirclePlus" @click="openUserDialog('新增')">新增用户</el-button>
				<el-button type="danger" :icon="Delete" plain @click="batchDelete(scope.selectedListIds)" :disabled="!scope.isSelected">
					批量删除用户
				</el-button>
			</template>
			<!-- 表格操作 -->
			<template #operation="scope">
				<el-button type="primary" link :icon="View" @click="openUserDialog('查看', scope.row)">查看</el-button>
				<el-button type="primary" link :icon="EditPen" @click="openUserDialog('编辑', scope.row)">编辑</el-button>
				<el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
			</template>
		</ProTable>
		<el-dialog v-model="userVisible" :title="userDialogTitle" :destroy-on-close="true" width="580px" draggable>
			<el-form label-width="100px" ref="userFormRef" label-suffix=" :" :rules="userRules" :model="userFormModel">
				<el-form-item label="用户姓名" prop="t_user_name">
					<el-input
						v-model="userFormModel.t_user_name"
						placeholder="请填写用户姓名"
						clearable
						:disabled="userDialogTitle == '查看'"
					></el-input>
				</el-form-item>
				<el-form-item label="性别" prop="t_gender">
					<el-select
						v-model="userFormModel.t_gender"
						placeholder="请选择性别"
						clearable
						style="width: 100%"
						:disabled="userDialogTitle == '查看'"
					>
						<el-option
							v-for="item in genderTypes"
							:key="item.code_value"
							:label="item.code_name"
							:value="item.code_value"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="年龄" prop="t_age">
					<el-input-number
						v-model="userFormModel.t_age"
						placeholder="请输入年龄"
						style="width: 100%"
						:controls="false"
						:min="1"
						:disabled="userDialogTitle == '查看'"
					></el-input-number>
				</el-form-item>
				<el-form-item label="身份证号" prop="t_idCard">
					<el-input
						v-model="userFormModel.t_idCard"
						placeholder="请输入身份证号"
						clearable
						:disabled="userDialogTitle == '查看'"
					></el-input>
				</el-form-item>
				<el-form-item label="用户状态" prop="t_status">
					<el-select
						v-model="userFormModel.t_status"
						placeholder="请选择用户状态"
						clearable
						style="width: 100%"
						:disabled="userDialogTitle == '查看'"
					>
						<el-option v-for="item in status" :key="item.value" :label="item.name" :value="item.value"></el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="userVisible = false">取消</el-button>
					<el-button type="primary" @click="handleSubmit"> 确认 </el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="tsx" setup name="useProTable">
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh } from "@element-plus/icons-vue";
import { onMounted, reactive, ref } from "vue";
import { addUserApi, deleteUserApi, editUserApi, getUseProTableListApi } from "@/api/modules/test/proTable";
import { getCodeKindsApi } from "@/api/modules/test/common";
import { useHandleData } from "@/hooks/useHandleData";
import { ElMessage, FormInstance } from "element-plus";
import { CodeKinds } from "@/interface";

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const useProTable = ref();

// 表格配置项
const columns: ColumnProps[] = [
	{ type: "selection", fixed: "left", width: 80 },
	{
		type: "index",
		label: "序号",
		width: 80
	},
	{
		prop: "t_user_name",
		label: "用户姓名",
		search: { el: "input", props: { placeholder: "请输入用户姓名" } },
		render: scope => {
			return (
				<el-button type="primary" link onClick={() => ElMessage.success("我是通过 tsx 语法渲染的内容")}>
					{scope.row.t_user_name}
				</el-button>
			)
		}
	},
	{
		prop: "t_gender",
		label: "性别",
		// 字典请求带参数
		enum: () => getCodeKindsApi({ code_kind: "gender" }),
		search: { el: "select" },
		fieldNames: { label: "code_name", value: "code_value" }
	},
	{
		prop: "t_age",
		label: "年龄",
		search: {
			// 自定义 search 显示内容
			render: ({ searchParam }) => {
				return (
					<div class="flx-center">
						<el-input vModel_trim={searchParam.minAge} placeholder="最小年龄" />
						<span class="mr10 ml10">-</span>
						<el-input vModel_trim={searchParam.maxAge} placeholder="最大年龄" />
					</div>
				);
			}
		}
	},
	{
		prop: "t_idCard",
		label: "身份证号"
	},
	{
		prop: "t_status",
		label: "用户状态",
		enum: [
			{
				label: "启用",
				value: 1
			},
			{
				label: "禁用",
				value: 0
			}
		],
		search: { el: "select" },
		render: scope => {
			// 渲染切换按钮
			return <el-switch model-value={scope.row.t_status} active-text={scope.row.t_status ? "启用" : "禁用"} active-value={1} inactive-value={0} onClick={() => changeStatus(scope.row)}></el-switch>
			// 渲染tag
			return <el-tag type={scope.row.t_status == 1 ? "success" : "danger"}>{scope.row.t_status == 1 ? "启用" : "禁用"}</el-tag>;
		}
	},
	{
		prop: "operation",
		label: "操作",
		width: 330
	}
];

const userVisible = ref(false);

const userDialogTitle = ref("新增");

const userRules = reactive({
	t_user_name: [{required: true, message: "请填写用户姓名", trigger: "blur"}],
	t_age: [{required: true, message: "请填写年龄", trigger: "blur"}],
	t_idCard: [{required: true, message: "请填写身份证号", trigger: "blur"}],
	t_status: [{required: true, message: "请选择用户状态", trigger: "blur"}],
	t_gender: [{required: true, message: "请选择性别", trigger: "blur"}],
})

let userFormModel = ref({
	t_user_id: "",
	t_user_name: "",
	t_age: "",
	t_idCard: "",
	t_status: "",
	t_gender: ""
})

// 获取性别分类
const genderTypes = ref<any>([])
const { data } = await getCodeKindsApi({code_kind: "gender"});
genderTypes.value = data; 

const status = ref([
	{
		name: "启用",
		value: 1
	},
	{
		name: "禁用",
		value: 0
	}
])

// 切换用户状态
const changeStatus = async (row: any) => {
	await useHandleData((params: any) => Promise<any>, {t_user_id: row.t_user_id, t_status: row.t_status}, "切换用户状态");
	useProTable.value?.getTableList();
}
// 删除用户
const deleteAccount = async (val: any) => {
	await useHandleData(deleteUserApi, {t_user_id: val.t_user_id}, '删除用户');
	useProTable.value.getTableList!();
};

// 批量删除用户
const batchDelete = async(id: string[]) => {
	await useHandleData(deleteUserApi, {t_user_id: id}, '删除所选用户信息');
	useProTable.value?.clearSelection();
	useProTable.value.getTableList!();
}

// 新增/修改/查看 用户
const openUserDialog = (title: string, row: any = {}) =>{
	userVisible.value = true;
	userDialogTitle.value = title;
	userFormModel.value = row;
}

// 提交数据
const userFormRef = ref<FormInstance>();
const handleSubmit = () => {
	userFormRef.value!.validate(async valid => {
		if (!valid) return;
		try {
			// 调用请求接口
			if (userDialogTitle.value == '新增') {
				await addUserApi(userFormModel.value)
			}
			else {
				await editUserApi(userFormModel.value);
			}
			ElMessage.success({ message: `${userDialogTitle.value}成功！` });
			useProTable.value.getTableList!();
			userVisible.value = false;
		} catch (error) {
			console.log(error)
		}
	})
}
</script>